/*
 * @Description: 用量和单位重量相关hook
 * @Author: chenju
 * @Date: 2022-07-13 11:07:02
 * @LastEditors: chenju
 * @LastEditTime: 2022-08-18 18:38:12
 */
import { computed, watch, toRefs } from 'vue';
import { weightUnitArr } from '@/constants/enum';
import { merge } from 'lodash';
import Decimal from 'decimal.js';
import { limitStrLength } from '@/utils';

interface UseWeightAndUnitNotModelParams<T> {
  // 入参表单
  props: T;
  // 配置
  options?: DefaultOptionsType;
  // 单位的类型变化时（重量单位/非重量单位的切换）
  onUnitTypeChange?: (isWeightUnit: boolean) => void;
}

interface ParamsPropsType {
  // 用量
  dosage: string;
  // 用量单位
  unit: string;
  // 单位重量
  weight: string;
  // 单位重量单位
  weightUnit: string;
}

interface DefaultOptionsType {
  isChangeNumWhenUnitChange: boolean;
}

const defaultOptions: DefaultOptionsType = {
  // 改变用量单位为重量单位时，计算用量的值（当前用量的值*单位重量）
  isChangeNumWhenUnitChange: true
};

export const useWeightAndUnitNotModel = <T extends ParamsPropsType>({
  props,
  options,
  onUnitTypeChange
}: UseWeightAndUnitNotModelParams<T>) => {
  const { dosage, unit, weight, weightUnit } = toRefs(props);
  options = merge(defaultOptions, options);

  console.log('useWeightAndUnitNotModel options', options);

  // 应该展示单位重量
  function shouldShowWeightUnit(unit: string | undefined) {
    if (!unit) return true;
    return !weightUnitArr.includes(unit);
  }

  // 是否是重量单位
  const isWeightUnitComputed = computed(() => {
    return weightUnitArr.includes(unit.value);
  });

  // 监听单位的类型变化
  watch(
    () => isWeightUnitComputed.value,
    (val: boolean) => {
      if (val) {
        if (options?.isChangeNumWhenUnitChange) {
          // NOTE 这里会直接改变原表单中的值
          if ((weight.value || weight.value === '0') && dosage.value) {
            dosage.value = limitStrLength(
              Decimal.mul(Number(dosage.value), Number(weight.value)).toNumber(),
              6,
              true
            );
          }
        }
        weightUnit.value = unit.value;
        weight.value = '1';
      }
      onUnitTypeChange && onUnitTypeChange(val);
    }
  );

  return {
    shouldShowWeightUnit,
    isWeightUnitComputed
  };
};
